<template>
  <view>
    <view class="popup">
      <up-popup
        :show="show"
        mode="bottom"
        :closeable="true"
        :safeAreaInsetBottom="false"
        @close="close"
        @open="open"
      >
        <view class="content">
          <view class="title text-xl margin-bottom-lg">请选择规格</view>
          <view class="padding-lr">
            <view class="skus">
              <view
                class="relative"
                v-for="(item, index) of $data.skuList"
                :key="index"
                @tap="onCheckSku(item)"
              >
                <view class="sku" :class="[{ 'sku--active': isActive(item) }]">
                  <view v-if="!!item.bindSku" class="group_tag">组合</view>
                  <view
                    class="sku_radio"
                    v-if="item.inputType === skuInputType.radio"
                  >
                    <view v-if="item._picurl" class="sku_radio__left">
                      <view class="sku_radio__left--image">
                        <up-image
                          :src="item._picurl"
                          width="120rpx"
                          height="120rpx"
                          :radius="10"
                        ></up-image>
                      </view>
                    </view>
                    <view
                      class="sku_radio__right"
                      :style="[
                        {
                          width: item._picurl ? 'calc(100% - 120rpx)' : '100%',
                        },
                      ]"
                    >
                      <!-- <view> -->
                      <view class="sku_radio__right--top">
                        <view class="sku_radio__right--top_title">
                          {{ item.skuTitle }}
                        </view>
                        <view
                          v-if="item.price != item.marketPrice"
                          class="sku_radio__right--top_price"
                        >
                          <text>预估到手价</text>
                          <text class="text-price">{{ item.price }}</text>
                        </view>
                      </view>
                      <view class="sku_radio__right--bottom">
                        <view class="sku_radio__right--bottom_desc">
                          {{ item.skuIntro }}
                        </view>
                        <view class="sku_radio__right--bottom_cost">
                          <text>原价</text>
                          <text class="text-price">{{ item.marketPrice }}</text>
                        </view>
                      </view>
                      <!-- </view> -->
                    </view>
                    <!-- <view class="sku_radio__left">
                      <view class="sku_radio__left--image">
                        <image :src="item._picurl" />
                      </view>
                      <view class="right-box">
                        <view class="sku_radio__left--title">
                          {{ item.skuTitle }}
                        </view>
                        <view
                          v-if="item.skuIntro"
                          class="sku_radio__left--desc"
                        >
                          {{ item.skuIntro }}
                        </view>
                      </view>
                    </view>
                    <view class="sku_radio__right">
                      <view
                        v-if="item.price != item.marketPrice"
                        class="sku_radio__right--price"
                      >
                        <text>预估到手价</text>
                        <text class="text-price">{{ item.price }}</text>
                      </view>
                      <view class="sku_radio__right--cost">
                        <text>原价</text>
                        <text class="text-price">{{ item.marketPrice }}</text>
                      </view>
                    </view> -->
                  </view>
                  <view
                    class="sku_input"
                    v-if="item.inputType === skuInputType.input"
                  >
                    <view class="sku_input__left">
                      <view v-if="item._picurl" class="sku_input__left--image">
                        <up-image
                          :src="item._picurl"
                          width="120rpx"
                          height="120rpx"
                          :radius="10"
                        ></up-image>
                      </view>
                      <view class="margin-left- right-box">
                        <view class="sku_input__left--title">
                          {{ item.skuTitle }}
                        </view>
                        <view class="sku_input__left--desc">
                          <text class="text-price">{{ item.price }}</text>
                          <text>/</text>
                          <text>{{ item.skuUnit }}</text>
                        </view>
                      </view>
                    </view>
                    <view
                      class="sku_input__right"
                      @tap.stop="onInputValue(item)"
                    >
                      <text class="sku_input__right--count">
                        <text v-if="item._value">
                          {{ item._value }}
                        </text>
                        <text v-else>请输入数量</text>
                      </text>
                      <text class="margin-left-sm">{{ item.skuUnit }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view v-if="tips" class="tips">
              <up-parse :content="tips"></up-parse>
            </view>
          </view>
          <view class="confirm">
            <view class="common_btn cancel_btn" @tap="close">关闭</view>
            <view class="common_btn confirm_btn" @tap="onSkuConfirm">确定</view>
          </view>
        </view>
      </up-popup>
    </view>
    <view class="input_popup">
      <up-popup
        :show="$data.inputShow"
        mode="center"
        :closeable="true"
        :safeAreaInsetBottom="false"
        @close="inputClose"
        @open="inputOpen"
      >
        <view class="input_content">
          <view class="input_title">输入框</view>
          <view class="input_box">
            <input
              v-model="$data.skuTarget._value"
              :min="0"
              type="number"
              placeholder="请输入数值"
            />
          </view>
          <view class="btns">
            <view class="btn" @tap="inputCancel">取消</view>
            <view class="btn" @tap="inputConfirm">确认</view>
          </view>
        </view>
      </up-popup>
    </view>
  </view>
</template>

<script setup>
import {
  reactive,
  ref,
  nextTick,
  computed,
  onMounted,
  watch,
  watchEffect,
} from "vue";
import BasicConfig from "../../utils/config";
import errorCode from "../../utils/http/errorCode";
import { getServiceSku } from "../../api/Interface/service";
import { useGetLocationStorage } from "../../hooks/useStorage";
import { skuInputType } from "../../enums/sku";
import { jumpPage } from "../../utils/route/route";
import { eventBus } from "../../enums/eventBus";
import { useImgSrc } from "../../hooks/useImg";
import { isDev } from "../../utils/env";
import { useTTPlugin } from "../../hooks/useTT";

const $emit = defineEmits(["update:show", "close", "choose"]);
const $props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  domesticServiceId: {
    type: [Number, String],
    default: "",
  },
  tips: {
    type: String,
    default: "",
  },
  /** 抖音直播传过来的skuId */
  tikTokSkuId: {
    type: [Number, String],
    default: "", // 246,
  },
});
const $data = reactive({
  skuList: [],
  isRadio: true, // 所有sku单选
  chooseSkuIds: [], // 选择的sku集合 单选isRadio===true时,只有一个元素,为了以后多选预留的
  inputShow: false, // 输入框
  skuTarget: { _value: "", _backupValue: "" }, // 要输入的目标sku对象
});
const formatTTSkuPrice = (sku) => {
  return new Promise((resolve) => {
    const NTT = useTTPlugin();
    let quantity = 1; // 数量
    if (sku.inputType == skuInputType.radio) {
      quantity = 1;
    }
    if (sku.inputType == skuInputType.input) {
      quantity = sku._value;
    }
    NTT.computePromotion({
      goodsMarketingInfo: [
        {
          goodsId: sku.dyProductId + "",
          quantity,
          totalAmount: Number(sku.dyPrice) * 100,
        },
      ],
      needDefaultMarketing: true, // 需要返回默认优惠
      success: (success) => {
        console.log("获取抖音优惠券 success", success);
        const { calculationResult } = success;
        if (calculationResult) {
          const { goodsCalculationResultInfo } = calculationResult;
          if (
            goodsCalculationResultInfo &&
            goodsCalculationResultInfo.length > 0
          ) {
            const { marketingDetailInfo } = goodsCalculationResultInfo[0];
            if (marketingDetailInfo && marketingDetailInfo.length > 0) {
              const discountInfo = marketingDetailInfo[0];
              if (discountInfo) {
                const { discountAmount } = discountInfo;
                const skuPrice = Number(sku.price) * 100; // 单位 分
                if (skuPrice > discountAmount) {
                  sku.price = ((skuPrice - discountAmount) / 100).toFixed(2);
                }
              }
            } else {
              const skuPrice = Number(sku.price) * 100;
              sku.price = ((skuPrice - 100) / 100).toFixed(2);
            }
          }
        }
      },
      fail: (fail) => {
        console.log("获取抖音优惠券 fail", fail);
      },
      complete: (c) => {
        console.log("获取抖音优惠券 complete", c);
        resolve();
      },
    });
  });
};
const init = () => {
  const { code = "2301" } = useGetLocationStorage();
  getServiceSku({
    cityCode: code,
    domesticServiceId: $props.domesticServiceId,
  }).then(async (res) => {
    if (res.code === errorCode.success) {
      BasicConfig.loadToast("加载中...");
      $data.skuList = res.data;
      for (const item of $data.skuList) {
        const imgs = item.dyCover.split(",") ?? [];
        if (imgs && imgs.length > 0) {
          item._picurl = useImgSrc(imgs[0]);
        } else item._picurl = "";
        item._value = "";
        item._backupValue = "";
        await formatTTSkuPrice(item);
      }
      if ($props.tikTokSkuId) {
        const sku = $data.skuList.find(
          (item) => item.domesticServiceSkuId == $props.tikTokSkuId
        );
        onCheckSku(sku);
        onSkuConfirm(false);
      } else if ($data.skuList.length > 0) {
        onCheckSku($data.skuList[0]);
        onSkuConfirm(false);
      }
      // // 如果只有1个sku,则直接选择
      // if ($data.skuList.length > 1) {
      //   const { domesticServiceSkuId } = $data.skuList[0];
      //   // 目前只考虑单选情况,不考虑有输入类型或者多选的sku
      //   $data.chooseSkuIds = [domesticServiceSkuId];
      //   onSkuConfirm();
      // }
    }
    uni.hideLoading();
  });
};
const onCheckSku = (e) => {
  const { domesticServiceSkuId: id, inputType } = e;
  // $data.isRadio = inputType == skuInputType.radio; // 输入的可以多选
  $data.isRadio = [skuInputType.radio, skuInputType.input].includes(inputType); // 都单选
  // 单选
  if ($data.isRadio) {
    $data.chooseSkuIds = [id];
  }
  // 多选
  else {
    if ($data.chooseSkuIds.includes(id)) {
      const index = $data.chooseSkuIds.findIndex((c) => c == id);
      $data.chooseSkuIds.splice(index, 1);
    } else {
      $data.chooseSkuIds.push(id);
    }
    _checkItem();
  }
  // onSkuConfirm(false);
};
const isActive = (e) => {
  const { domesticServiceSkuId: id } = e;
  return $data.chooseSkuIds.includes(id);
};
/**
 * 确认sku选择
 * @param popup 是否弹出购买,如果用户从列表点击进来,并且只有一个sku那么不弹出
 */
const onSkuConfirm = (popup = true) => {
  if ($data.chooseSkuIds.length === 0) {
    BasicConfig.toast("请选择规格");
    return;
  }
  let chooseSkus = [];
  for (const id of $data.chooseSkuIds) {
    const sku = $data.skuList.find((s) => s.domesticServiceSkuId == id);
    if (sku.inputType == skuInputType.input && !sku._value) {
      BasicConfig.toast("请输入sku数量");
      chooseSkus = [];
      return;
    } else {
      chooseSkus.push(sku);
    }
  }
  console.log("选择的sku", chooseSkus);
  $emit("choose", $props.domesticServiceId, chooseSkus, popup);
  close();
};
/**
 * 点击sku后
 * 如果点击的是可输入的,并且chooseSkuIds里有单选的,删掉
 */
const _checkItem = () => {
  $data.chooseSkuIds.forEach((id, i) => {
    const skuItem = $data.skuList.find((s) => s.domesticServiceSkuId == id);
    // 删掉单选的
    if (skuItem.inputType == skuInputType.radio) {
      $data.chooseSkuIds.splice(i, 1);
    }
  });
};
/** 输入数字弹窗显示 */
const onInputValue = (e) => {
  const { domesticServiceSkuId: id } = e;
  $data.isRadio = true; // 输入的可以多选
  if (!$data.chooseSkuIds.includes(id)) {
    $data.chooseSkuIds.push(id);
  }
  _checkItem();
  $data.inputShow = true;
  $data.skuTarget = e;
};
const close = () => {
  $emit("update:show", false);
};
const open = () => {
  // init();
};
const inputCancel = () => {
  $data.skuTarget._value = $data.skuTarget._backupValue;
  inputClose();
};
const inputConfirm = () => {
  const { _value } = $data.skuTarget;
  const value = Number(_value);
  if (value && value >= 1) {
    $data.inputShow = false;
    $data.skuTarget = { _value: "", _backupValue: "" };
  } else {
    BasicConfig.toast("请填写数量(数量需大于0)");
  }
};
const inputClose = () => {
  $data.inputShow = false;
  $data.skuTarget = { _value: "", _backupValue: "" };
};
const inputOpen = () => {
  $data.skuTarget._backupValue = $data.skuTarget._value;
};
onMounted(() => {
  init();
});
</script>
<script>
// 小程序穿透
export default {
  options: { styleIsolation: "shared" },
};
</script>
<style lang="scss" scoped>
.popup {
  ::v-deep .u-popup__content {
    border-radius: 30rpx 30rpx 0 0 !important;
    max-height: 70vh;
    z-index: 9999;
  }
  .content {
    background: #ffffff;
    border-radius: 30rpx 30rpx 0 0;
    max-height: 70vh;
    // padding: 30rpx;
    padding-bottom: 300rpx;
    // padding-top: 30rpx;
    overflow-y: auto;
    position: relative;
    z-index: 9999;
    .title {
      position: sticky;
      top: 0;
      background: #ffffff;
      z-index: 9999;
      padding: 30rpx;
    }
    .skus {
      margin-top: 30rpx;
      position: relative;
      .sku {
        padding: 30rpx;
        border-radius: 20rpx;
        background: #f7f8fa;
        margin-bottom: 30rpx;
        position: relative;
        .group_tag {
          position: absolute;
          left: 0;
          top: 0;
          color: #ffffff;
          background: #bbbbbb;
          width: max-content;
          border-radius: 20rpx 0 20rpx 0;
          padding: 6rpx 10rpx;
        }
        &--active {
          background: #e4f9f9 !important;
          border: 2rpx solid $main-color !important;
          color: $main-color !important;
          ::v-deep view {
            color: $main-color !important;
          }
          .group_tag {
            color: #ffffff !important;
            background: $main-color !important;
          }
        }
        .right-box {
          width: calc(100% - 120rpx);
          margin-left: 30rpx;
        }
        &_radio {
          display: flex;
          align-items: center;
          &__left {
            width: 120rpx;
            display: flex;
            align-items: center;

            &--image {
              width: 120rpx;
              height: 120rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              image {
                width: 100%;
                height: 100%;
                border-radius: 20rpx;
              }
            }
          }
          &__right {
            width: calc(100% - 120rpx);
            margin-left: 30rpx;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            &--top {
              display: flex;
              justify-content: space-between;
              align-items: flex-start;
              &_price {
                color: $main-color;
                text-align: right;
                text {
                  &:first-child {
                    font-size: 30rpx;
                  }
                  &:last-child {
                    font-size: 44rpx;
                    margin-left: 20rpx;
                  }
                }
              }
              &_title {
                font-size: 34rpx;
                font-weight: 700;
              }
            }
            &--bottom {
              display: flex;
              justify-content: space-between;
              align-items: flex-start;
              margin-top: 20rpx;
              &_cost {
                font-size: 32rpx;
                color: #333333;
                text-align: right;
                // margin-top: 20rpx;
                text-decoration: line-through;
                &:first-child {
                  font-size: 28rpx;
                }
                &:last-child {
                  margin-left: 20rpx;
                }
              }
              &_desc {
                font-size: 32rpx;
                color: #666666;
                // margin-top: 20rpx;
              }
            }
          }
        }
        &_input {
          display: flex;
          align-items: center;
          &__left {
            display: flex;
            align-items: center;
            width: calc(100% - 300rpx);
            &--image {
              width: 120rpx;
              height: 120rpx;
              image {
                width: 100%;
                height: 100%;
                border-radius: 20rpx;
              }
            }
            &--title {
              font-size: 34rpx;
              font-weight: 700;
            }
            &--desc {
              font-size: 32rpx;
              color: #666666;
              margin-top: 20rpx;
              display: flex;
            }
          }
          &__right {
            width: 300rpx;
            // display: flex;
            // align-items: center;
            font-size: 34rpx;
            text-align: right;
            color: #333333;
            // height: 100%;
            // input {
            //   text-align: right;
            //   font-size: 40rpx;
            // }
            &--count {
              font-size: 44rpx;
            }
          }
        }
      }
    }
    .tips {
      margin: 30rpx 0;
    }
    .confirm {
      width: 100%;
      margin: 30rpx 0 0 0;
      padding: 30rpx;
      background: #ffffff;
      z-index: 9999;
      position: fixed;
      bottom: 0;
      display: flex;
      align-items: center;
      .cancel_btn {
        width: 30%;
      }
      &_btn {
        width: 70%;
        margin-left: 30rpx;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.input_popup {
  ::v-deep .u-popup__content {
    border-radius: 30rpx !important;
    // padding: 30rpx;
  }
  .input_content {
    background: #ffffff;
    border-radius: 30rpx;
    height: 100%;
    padding: 30rpx;
    width: 80vw;
    .input_title {
      text-align: center;
      font-size: 40rpx;
    }
    .input_box {
      border-bottom: 1px solid #f0f0f0;
      margin: 40rpx 0;
      padding: 30rpx;
      input {
        font-size: 34rpx;
      }
    }

    .btns {
      margin-top: 60rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .btn {
        border-radius: 100rpx;
        padding: 20rpx 30rpx;
        width: 46%;
        text-align: center;
        font-size: 34rpx;
        &:first-child {
          background: #ffffff;
          border: 1px solid #cccccc;
          color: #333333;
        }
        &:last-child {
          background: $main-color;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
